package action

import (
	"fmt"
	"gitee.com/dromara/carbon/v2"
	"github.com/spf13/cast"
	"server/component"
	"server/im/entity"
	"server/im/online"
	"server/im/protocol"
)

// 私聊消息
func ActionPrivateMsg(ctx entity.ServiceContext) {
	var reqData map[string]string
	component.JsonDecode(ctx.Data, &reqData)

	toUUid, ok1 := reqData["to_uuid"]
	talkId, ok2 := reqData["talk_id"]
	msg, ok3 := reqData["msg"]
	if !(ok1 && ok2 && ok3) {
		component.Log.Error(fmt.Printf("private msg err %+v \n", ctx.Data))
		return
	}
	toUUidStr := cast.ToString(toUUid)
	talkIdStr := cast.ToString(talkId)
	msgStr := cast.ToString(msg)

	sendClients := []string{ctx.User.Uuid}
	isOnline := online.OnlineMap.IsUserOnline(entity.UserModel{Uuid: toUUidStr})
	if isOnline {
		sendClients = append(sendClients, toUUidStr)
	} else { //todo 离线消息
	}

	sendMsg := map[string]string{
		"talk_id": talkIdStr,
		"msg":     msgStr,
		"name":    ctx.User.Name,
		"uuid":    ctx.User.Uuid,
		"time":    carbon.Now().ToDateTimeString(),
	}
	msgBytes, err := component.JsonEncode(sendMsg)
	if err != nil {
		component.Log.Error(err)
		return
	}
	ctx.RespChan <- entity.CoreResultModel{
		CoreOutModel: entity.CoreOutModel{
			GatewayOutModel: entity.GatewayOutModel{
				Data: msgBytes,
				Cmd:  protocol.RespPrivateChatMsg,
			},
			GatewayId:    ctx.GatewayId,
			MsgType:      entity.MsgTypeNormal,
			ReceiverType: entity.ReceiverTypeGroup,
			Clients:      sendClients,
		},
		ResultType: entity.CoreResultTypeAll,
	}

	return

}
